﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using crmbl.Azure.Globals;
using crmbl.Azure.WorkProcessor.Library;

namespace crmbl.Azure.WorkProcessor
{
    public class WorkProcessorData : IDisposable
    {

        WorkProcessorConfig _config;
        SqlHelper _sql;

        public WorkProcessorData(WorkProcessorConfig config)
        {
            _config = config;

            // Initiate the Sql Connection
            _sql = new SqlHelper(config.ConfigurationConnectionString);
        }


        #region Scheduler

        public List<WorkDefinition> GetNextWorkToSchedule()
        {
            // TODO: Yea, this isn't right, re-evaluate

            List<WorkDefinition> worky = new List<WorkDefinition>();

            var toSchedule = from l in worky
                             where 
                                // Time
                                l.StartDateTimeUTC < DateTime.Now.AddSeconds(_config.TimeWindowSeconds)
                                // Verify Locked
                                && (
                                    // Check for locked
                                    l.LockKey == null
                                    // Check for exired lock
                                    | l.LastLockedDateTime > DateTime.Now.AddSeconds(_config.TimeWindowSeconds).AddSeconds(1)
                                    )
                             select l;

            return toSchedule.ToList();

        }


        public void SaveWorkScheduleToQueue(List<WorkDefinition> work)
        {
            foreach (WorkDefinition w in work)
            {
                WriteWorkToQueue(w);
            }
        }

        private void WriteWorkToQueue(WorkDefinition work)
        {
            throw new NotImplementedException();
        }


        #endregion


        #region Runner

        public WorkDefinition? GetNextWorkFromQueue()
        {
            throw new NotImplementedException();
        }


        #endregion

        public void Dispose()
        {
            try
            {
                _sql.Dispose();
            }
            catch (Exception ex)
            {
                // ignore
            }
        }
    }
}
